/*
 * @Author: YWY
 * @Date: 2022-02-24 13:16:54
 * @LastEditors: YWY
 * @LastEditTime: 2022-03-07 08:24:19
 */
import { defineStore } from "pinia";
import { disFollowUser, getFans, getOwnArticle, getUserFavorite, getUserFollows, uploadUserData, uploadUserPic, getTotalLikes } from "../api/services/user.service";

export const userStore = defineStore('user', {
    state: () => {
        return {
            id: 1,
            name: '路人甲',
            nameInput: "",
            sex: '男',
            city: '杭州',
            avatar: "http://localhost:3000/src/assets/image/userImg.png",
            pic: [],
            article: [],
            favorite: [],
            follows: [],
            fans: [],
            likes: 0
        }
    },
    actions: {

        // 上传资料
        upload() {
            let picres = Promise.resolve();
            if (this.pic[0]) {
                console.log(this.pic[0])
                const formData = new FormData();
                formData.append("file", this.pic[0].file)
                picres = uploadUserPic(formData);
            }
            let datares = uploadUserData(this.nameInput, this.sex, this.city)
            return Promise.all([picres, datares])
        },


        //获取用户发表文章
        async loadUserAticle() {
            let res = await getOwnArticle()
            return res.result.article_list
        },

        //获取用户收藏
        async loadUserFavorite() {
            let res = await getUserFavorite();
            return res.result
        },

        //获取用户关注列表
        async loadUserFollows() {
            let res = await getUserFollows(this.id);
            return res.res;
        },

        //取消关注
        async deletFollower(id) {
            disFollowUser(id).then(res => {
                console.log(res)
            });
        },

        //获取用户粉丝列表
        async loadUserFans() {
            let res = await getFans(this.id);

            return res.res
        },

        logIn(data) {
            console.log(data)
            let avatarData = data.img;
            this.$patch({
                name: data.name,
                id: data.id,
                city: data.city,
                sex: data.sex,
                avatar: avatarData
            })
        },

        //获取被点赞总数
        async loadTotalLikes() {
            let res = await getTotalLikes(this.id);
            console.log(res)
            return res.result.cnt ? res.result.cnt : 0
        },


        //页面初始化
        async init() {
            this.$patch(
                {
                    article: await this.loadUserAticle(),
                    favorite: await this.loadUserFavorite(),
                    follows: await this.loadUserFollows(),
                    fans: await this.loadUserFans(),
                    likes: await this.loadTotalLikes()
                }
            )
        }

    }
})